package com.thkj.modules.user.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeoutException;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.google.code.kaptcha.Producer;
import com.thkj.common.util.RmUtil;
import com.thkj.common.util.Util;
import com.thkj.modules.user.entity.TblSecurityAdmin;
import com.thkj.modules.user.service.ILoginRecordService;
import com.thkj.modules.user.service.TblSecurityAdminService;

import dp.R;
import dp.web.BaseAction;

@RestController
@RequestMapping("/user")
public class UserAction extends BaseAction {
    @Resource
    TblSecurityAdminService tblSecurityAdminService;
    @Resource
    ILoginRecordService loginRecordService;
    @Resource
    Producer captchaProducer;

    private static final String KAPTCHA_SESSION_KEY = "KAPTCHA_SESSION_KEY";

    /**
     * 生成验证码，把验证码加密放入session
     *
     * @throws IOException
     * @throws InterruptedException
     * @throws TimeoutException
     */
    @RequestMapping("/captcha")
    public void captcha() throws IOException, TimeoutException, InterruptedException {
        HttpServletResponse response = this.getResponse();
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        String capText = captchaProducer.createText();
        //使用session
        this.getRequest().getSession().setAttribute(KAPTCHA_SESSION_KEY, capText);

        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.setUseCache(false);
        ImageIO.write(bi, "jpg", out);
    }

    @RequestMapping("/index")
    public ModelAndView index(HttpServletRequest request) {
        String requestHeader = request.getHeader("user-agent");
        if (Util.isMobileDevice(requestHeader)) {
            return new ModelAndView("index/index");
        } else {
            return new ModelAndView("index/index");
        }
    }

    /**
     * 登录
     */
    @RequestMapping("/login")
    public R login(String userCode, String password, String captcha) {
        if (StringUtils.isBlank(userCode) || StringUtils.isBlank(password)) {
            return R.failure("用户名密码不能为空");
        }

        //从session获取删除图形验证码，防止重复提交
        String kaptcha_session_key = (String) this.getRequest().getSession().getAttribute(KAPTCHA_SESSION_KEY);
        this.getRequest().getSession().removeAttribute(KAPTCHA_SESSION_KEY);

        if (StringUtils.isBlank(kaptcha_session_key) || !kaptcha_session_key.equals(captcha)) {
            return R.failure("验证码错误");
        }

        //验证通过，向cookie写入加密的字符串
        TblSecurityAdmin rmPerson = tblSecurityAdminService.validatePassword(userCode, password);
        if (rmPerson != null) {
            RmUtil.setLoginUserInfoAtCookie(this.getResponse(), rmPerson);
            try {
            	loginRecordService.save(rmPerson);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("保存登录记录出现异常:===" + e.getMessage());
            }
            return R.success("user/crossdomain");
        } else {
            return R.failure("用户名密码错误");
        }
    }

    /**
     * 退出
     */
    @RequestMapping("/logout")
    public void logout() throws IOException {
        RmUtil.clearLoginUserInfoFromCookie(this.getResponse());
        this.getResponse().setHeader("REFRESH", "0;URL=../");
    }

    /**
     * 设置跨域
     */
    @RequestMapping("/crossdomain")
    public void crossdomain() throws IOException {
        this.getResponse().setHeader("REFRESH", "0;URL=../desktop");
    }

    @RequestMapping("/desktop")
    public ModelAndView desktop() {
        this.getRequest().setAttribute("user", RmUtil.getLoginUser(this.getRequest()));
        if ("true".equals(this.getRequest().getAttribute("isMobile").toString())) {
            return new ModelAndView("index/desktop");
        } else {
            return new ModelAndView("index/desktop");
        }
    }

    @RequestMapping("/noAuthorize")
    public ModelAndView noAuthorize() {
        return new ModelAndView("noAuthorize");
    }
}
